from config.db_connection import DBConnection
import pymysql
from datetime import datetime, timedelta

class Order:
    """订单信息数据类"""
    
    def __init__(self, order_data=None):
        """初始化订单信息"""
        if order_data:
            self.id = order_data.get('id', 0)
            self.product_name = order_data.get('product_name', '')
            self.price = float(order_data.get('price', 0.0))
            self.customer_phone = order_data.get('customer_phone', '')
            self.customer_name = order_data.get('customer_name', '')
            self.delivery_status = order_data.get('delivery_status', 0)
            self.order_time = order_data.get('order_time', None)
            self.expected_delivery_time = order_data.get('expected_delivery_time', None)
        else:
            self.id = 0
            self.product_name = ''
            self.price = 0.0
            self.customer_phone = ''
            self.customer_name = ''
            self.delivery_status = 0
            self.order_time = None
            self.expected_delivery_time = None
    
    def get_status_text(self):
        """获取订单状态文本"""
        status_map = {
            0: "待派发",
            1: "派送中", 
            2: "已完成"
        }
        return status_map.get(self.delivery_status, "未知状态")
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'product_name': self.product_name,
            'price': self.price,
            'customer_phone': self.customer_phone,
            'customer_name': self.customer_name,
            'delivery_status': self.delivery_status,
            'order_time': self.order_time,
            'expected_delivery_time': self.expected_delivery_time
        }
    
    def __str__(self):
        return f"Order(id={self.id}, product='{self.product_name}', status='{self.get_status_text()}')"

class OrderModel:
    """订单数据模型"""
    
    @staticmethod
    def create_order(product_name, price, customer_phone, customer_name):
        """创建订单"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            # 计算预计送达时间（当前时间+30分钟）
            expected_time = datetime.now() + timedelta(minutes=30)
            
            # 插入新订单
            cursor.execute("""
                INSERT INTO `order` (product_name, price, customer_phone, customer_name, 
                                   delivery_status, expected_delivery_time) 
                VALUES (%s, %s, %s, %s, 0, %s)
            """, (product_name, price, customer_phone, customer_name, expected_time))
            
            order_id = cursor.lastrowid
            conn.commit()
            print(f"订单创建成功，订单号: {order_id}")
            return order_id
            
        except pymysql.Error as e:
            print(f"创建订单失败: {e}")
            conn.rollback()
            return None
        finally:
            cursor.close()
    
    @staticmethod
    def get_orders_by_customer(customer_phone):
        """根据客户手机号获取订单信息 - 每次都从数据库重新查询"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            print(f"查询手机号 {customer_phone} 的订单")  # 调试信息
            
            cursor.execute("""
                SELECT id, product_name, price, customer_phone, customer_name, 
                       delivery_status, order_time, expected_delivery_time
                FROM `order` 
                WHERE customer_phone = %s 
                ORDER BY order_time DESC
            """, (customer_phone,))
            
            orders = cursor.fetchall()
            order_list = []
            
            print(f"数据库返回 {len(orders)} 条记录")  # 调试信息
            
            for order in orders:
                print(f"订单 {order[0]} 状态: {order[5]}")  # 调试订单状态
                order_data = {
                    'id': order[0],
                    'product_name': order[1],
                    'price': order[2],
                    'customer_phone': order[3],
                    'customer_name': order[4],
                    'delivery_status': order[5],
                    'order_time': order[6],
                    'expected_delivery_time': order[7]
                }
                order_list.append(Order(order_data))
        
            return order_list
        
        except pymysql.Error as e:
            print(f"获取订单信息失败: {e}")
            return []
        finally:
            cursor.close()
    
    @staticmethod
    def get_all_orders():
        """获取所有订单（管理员用）"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            cursor.execute("""
                SELECT id, product_name, price, customer_phone, customer_name, 
                       delivery_status, order_time, expected_delivery_time
                FROM `order` 
                ORDER BY order_time DESC
            """)
            
            orders = cursor.fetchall()
            order_list = []
            
            for order in orders:
                order_data = {
                    'id': order[0],
                    'product_name': order[1],
                    'price': order[2],
                    'customer_phone': order[3],
                    'customer_name': order[4],
                    'delivery_status': order[5],
                    'order_time': order[6],
                    'expected_delivery_time': order[7]
                }
                order_list.append(Order(order_data))
            
            return order_list
            
        except pymysql.Error as e:
            print(f"获取订单列表失败: {e}")
            return []
        finally:
            cursor.close()
    
    @staticmethod
    def update_order_status(order_id, new_status):
        """更新订单状态"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            cursor.execute("""
                UPDATE `order` SET delivery_status = %s WHERE id = %s
            """, (new_status, order_id))
            
            conn.commit()
            print(f"订单 {order_id} 状态更新为: {new_status}")
            return True
            
        except pymysql.Error as e:
            print(f"更新订单状态失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
    
    @staticmethod
    def confirm_delivery(order_id):
        """确认收货（用户操作）"""
        return OrderModel.update_order_status(order_id, 2)
    
    @staticmethod
    def start_delivery(order_id):
        """开始派送（管理员操作）"""
        return OrderModel.update_order_status(order_id, 1)